<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElButton, ElLoading } from 'element-plus'
import axios from 'axios'
import { useDataStore } from '@/stores/choose.js'
import { useTagStore } from '@/stores/tags.js'
import Tags from '@/views/home/components/tags.vue'
import Cascader from "@/components/Cascader.vue"

const router = useRouter()
const dataStore = useDataStore()
const tagStore = useTagStore()

// 数据状态
const selectedValues = ref([])
const isMounted = ref(false)

// API 配置
const apiConfig = {
  getTopLevel: () => axios.get('/api/zyTree/level/1', {
    headers: {
      Authorization: 'Bearer ' + localStorage.getItem('jwt_token'),
    }
  }),
  getChildren: (params) => axios.get('/api/zyTree/children', {
    headers: {
      Authorization: 'Bearer ' + localStorage.getItem('jwt_token'),
    },
    params
  })
}

// 初始化加载
onMounted(() => {
  isMounted.value = true
})

// 处理选择变化
const handleChange = (values) => {
  console.log('选中值变化:', values)
  selectedValues.value = values
}

// 处理搜索按钮点击
const handleClick = async () => {
  if (selectedValues.value.length === 0) {
    console.warn('No options selected')
    return
  }

  const loadingService = ElLoading.service({
    lock: true,
    text: '正在拼命加载中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  try {
    tagStore.clearTempData()
    await router.push(tagStore.tagList[0].path)
    dataStore.setSelectedOptions(selectedValues.value)
    selectedValues.value = []
  } finally {
    loadingService.close()
  }
}

// 导出 Excel
const downloadExcel = async () => {
  const url = 'http://localhost:8081/export'
  const jwtToken = localStorage.getItem('jwt_token')

  try {
    const response = await axios({
      url,
      method: 'GET',
      headers: { Authorization: 'Bearer ' + jwtToken },
      responseType: 'blob',
    })

    // 解析文件名
    const contentDisposition = response.headers['content-disposition'] || response.headers['Content-Disposition']
    let fileName = 'Model.xlsx'

    if (contentDisposition) {
      const filenameRegex = /filename\*?=['"]?(?:UTF-\d['"]*)?([^;\r\n"']*)['"]?/i
      const matches = contentDisposition.match(filenameRegex)
      if (matches && matches[1]) {
        fileName = decodeURIComponent(matches[1].trim())
          .replace(/['"]/g, '')
          .replace(/\s+/g, '_')
      }
    }

    // 创建下载链接
    const blob = new Blob([response.data], {
      type: response.headers['content-type'] ||
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    })
    const downloadUrl = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = downloadUrl
    link.download = fileName
    link.style.display = 'none'

    // 触发下载
    document.body.appendChild(link)
    link.click()

    // 清理资源
    setTimeout(() => {
      document.body.removeChild(link)
      window.URL.revokeObjectURL(downloadUrl)
    }, 100)
  } catch (error) {
    console.error('文件下载失败:', {
      status: error.response?.status,
      message: error.message,
    })
    if (error.response?.status === 500) {
      alert('服务器文件生成失败，请重试')
    }
  }
}
</script>

<template>
  <div class="container">
    <div class="row row1">
      <label style="margin-left: 10px">河北省本科高校专业发展数据平台(内部测试平台)</label>
    </div>

    <div class="row row2">
      <Cascader
        v-model="selectedValues"
        :api-config="apiConfig"
        @change="handleChange"
        style="width: 95%"
      />

      <el-button
        type="primary"
        style="margin-left: 5px; background-color: #05558f"
        @click="handleClick"
      >
        搜索
      </el-button>
    </div>

    <Tags />
    <router-view ref="childComponent" key="key"></router-view>
  </div>
</template>

<style>
body {
  overflow: hidden; /* 隐藏滚动条且禁止滚动 */
}

.container {
  display: flex;
  flex-direction: column;
  height: 100vh; /* 使容器高度占满整个视口 */
}

.row {
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
}

.row1 {
  background-color: #419ded;
  height: 6vh;
  font-size: 30px;
  justify-content: flex-start;
}

.row2 {
  background-color: #ffffff;
  height: 6vh;
  justify-content: flex-start;
}

.row3 {
  background-color: green;
  height: 75vh;
}

.row4 {
  display: flex;
  align-items: center;
  height: 4vh;
  background-color: #ffffff;
  color: #808080;
}


</style>
